package com.cqut.util;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.innosystec.unrar.Archive;
import de.innosystec.unrar.exception.RarException;
import de.innosystec.unrar.rarfile.FileHeader;


/**
 * 
 * @author heyanqiu
 * rar 压缩包解压
 *
 */
public class RarUtil {
	

	/** 
     * 解压rar格式的压缩文件到指定目录下 
     * @param rarFileName 压缩文件 (包括路径)如：c:\\temp\\123.rar
     * @param extPlace 解压目录   如:c:\\temp
     * @throws Exception 
     */ 
	public void unrarFiles(String rarFileName, String extPlace) {
		Archive archive = null;
		File out = null;
		File file = null;
		File dir = null;
		FileOutputStream os = null;
		String fileName = "";
		FileHeader fh = null;
		String path, dirPath = "";
		try {
			file = new File(rarFileName);    //创建文件
			archive = new Archive(file);     //实例化Archive对象
		} catch (RarException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (file != null) {
				file = null;
			}
		}
		if (archive != null) {
			try {
				fh = archive.nextFileHeader();
				while (fh != null) {
					fileName=  fh.getFileNameW().trim();
					if(!existZH(fileName)){
						fileName = fh.getFileNameString().trim();
					}
					path = (extPlace + fileName).replaceAll("\\\\", "/");
					int end = path.lastIndexOf("/");
					if (end != -1) {
						dirPath = path.substring(0, end);
					}
					try {
						dir = new File(extPlace);
						if (!dir.exists()) {
							dir.mkdirs();
						}
					} catch (RuntimeException e1) {
						e1.printStackTrace();
					} finally {
						if (dir != null) {
							dir = null;
						}
					}
					if (fh.isDirectory()) {
						fh = archive.nextFileHeader();
						continue;
					}
					out = new File(extPlace + "\\" + fileName);
					try {
						os = new FileOutputStream(out);
						archive.extractFile(fh, os);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (RarException e) {
						e.printStackTrace();
					} finally {
						if (os != null) {
							try {
								os.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						if (out != null) {
							out = null;
						}
					}
					fh = archive.nextFileHeader();
					System.out.println("解压:"+fileName);
				}
			} catch (RuntimeException e) {
				e.printStackTrace();
			} finally {
				fh = null;
				if (archive != null) {
					try {
						archive.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	//判断是否含有中文字符
	public static boolean existZH(String str) {
		String regEx = "[\\u4e00-\\u9fa5]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		while (m.find()) {
			return true;
		}
		return false;
	}
}
